import type { CSSProperties } from "vue";
import type { Align, Color, ImageFit, Numberic, PtComponent, PtComponentConst, Source, Vertical } from "../../../types";
import type { PtContainer, PtPage } from '../../../types';
import type { PtData } from "@/modules/pt-page/src/PtData";
import { previewImage } from "@/modules/pt-page/functions";

export const name = 'image';

type ComponentType = typeof name;

export interface Props {
    src: string;
}

export interface RenderOptions {
    // 图片填充模式，默认fill
    fit: ImageFit;
    // 图片填充模式位置，默认center
    fitAlign: Align;
    fitVertical: Vertical;
    // 边框颜色
    borderColor: Color;
    // 边框宽度
    borderWidth: Numberic;
    // 边框圆角，-1为正圆（相当于100%圆角）
    borderRadius: Numberic;
    // 背景
    background: string;
    // 是否可预览
    preview: boolean;
}

export interface ThisComponent extends PtComponent<ComponentType, Props, RenderOptions> {}

export const render = (instance: PtContainer, comp: ThisComponent | PtComponentConst, _parentComp?: PtComponentConst, data?: PtData): JSX.Element => {
    const { value, render } = comp;

    const getPosition = (): string => {
        return [
            render.fitAlign ? render.fitAlign : 'center',
            render.fitVertical ? render.fitVertical == 'middle' ? 'center' : render.fitVertical : 'center',
        ].join(' ');
    }

    const getBorder = (): string => {
        if (!render.borderWidth) {
            return '';
        }

        return `${instance.style.calcSize(render.borderWidth)} solid ${render.borderColor || '#fff'}`;
    }

    const src = (data ? data : instance.data).getString(value.src);

    const style: CSSProperties = {
        position: 'relative',
        width: '100%',
        height: '100%',
        border: getBorder(),
        borderRadius: instance.style.getRadiusSize(render.borderRadius),
        backgroundImage: `url(${src})`,
        backgroundColor: render.background || render.borderColor || '',
        backgroundOrigin: getPosition(),
        backgroundSize: render.fit || 'fill',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat',
    }

    const onClickImage = () => {
        if (render.preview) {
            previewImage(src);
        }
    }

    return (<div style={style} onClick={onClickImage}></div>)
}

export const getPreloadSource = (instance: PtPage, comp: ThisComponent | PtComponentConst, data?: PtData): Source[] => {
    return [
        {
            type: 'image',
            src: data?.getString(comp.value.src) || '',
            raw: data?.getString(comp.value.src) || '',
        }
    ];
}